<template>
  <div v-loading="loading" class="customer_type" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addType"> 添加分类</HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">批量启用</el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">批量禁用</el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">批量删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model.trim="typeInput"
          placeholder="名称搜索"
          clearable
          @keyup.enter="getTypeData"
          @clear="getTypeData"
        />
        <HButton type="primary" @click="getTypeData">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <div class="table">
      <el-table
        ref="typeTable"
        border
        stripe
        resizable
        :data="typeList"
        height="100%"
        row-key="id"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="40" fixed="left" :align="'center'" />
        <el-table-column type="index" label="序号" width="65" fixed="left" :align="'center'" />
        <el-table-column show-overflow-tooltip prop="name" label="分类名称" />
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column prop="status" label="状态" width="70" fixed="right" :align="'center'">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="scope.row.status === false">启用</HStatus>
              <HStatus v-if="scope.row.status === true" type="info">禁用</HStatus>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="90">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink @click="viewTypeDetail(scope.row)">编辑</HLink>
              <h-link type="error" @click="handleDel(scope.row)">删除</h-link>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <Pagination
        ref="typePaginDom"
        :list_total="typeTotal"
        @size-change="getTypeData"
        @current-change="getTypeData(false)"
      />
    </div>
    <!-- 添加/编辑  分类弹窗 -->
    <h-dialog v-model="addDialog" :title="typeForm.title" :loading="typeLoading">
      <el-form
        ref="typeFormRef"
        :rules="typeRules"
        :model="typeForm"
        class="modal_form_content"
        label-position="top"
        inline-message
        @submit.prevent
      >
        <el-form-item label="分类名称" class="form-item" prop="name">
          <el-input
            v-model.trim="typeForm.name"
            clearable
            placeholder="请输入名称"
            @keyup.enter="saveType(typeFormRef)"
          />
        </el-form-item>
        <el-form-item label="分类状态" class="same_line">
          <el-radio-group v-model="typeForm.status">
            <el-radio :value="false" size="small">启用</el-radio>
            <el-radio :value="true" size="small">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <HButton type="primary" is-modal @click="saveType(typeFormRef)">保存</HButton>
        <HButton is-modal @click="addDialog = false">取消</HButton>
      </template>
    </h-dialog>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, onMounted, reactive, h } from 'vue'
  import { Search, ArrowDown } from '@element-plus/icons-vue'
  import { ElDivider, ElMessage, ElMessageBox, TableInstance } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { getTypeList, saveUserType, changeType, deleteType } from '@/api/users'
  import { CustomerType } from './types'

  const handleDel = (customerType: CustomerType) => {
    if (typeTable.value) {
      typeTable.value.clearSelection()
      typeTable.value.toggleRowSelection(customerType, true)
      changeStatus(3)
    }
  }

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  // 用户分类数据
  const typeForm = reactive({
    id: null,
    name: '',
    status: false,
    title: '',
  })

  const typeLoading = ref(false)
  const typeList = ref([]) // 列表数据
  const typeTable = ref<TableInstance | null>(null) // 列表dom
  const typeInput = ref('') // 搜索框
  const typePaginDom = ref() // 分页dom
  const typeTotal = ref() // 总数目
  const typeFormRef = ref<FormInstance>() // 表单元素

  const typeRules = reactive({
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  })

  const loading = ref(false)
  const addDialog = ref(false)

  const props = defineProps({
    active_name: String,
  })

  onMounted(() => {
    if (props.active_name == 'type') {
      getTypeData()
    }
  })

  // 获取分类列表
  const getTypeData = async (val = true) => {
    loading.value = true
    if (val) typePaginDom.value.setPage()
    const data = {
      limit: typePaginDom.value.size,
      name: typeInput.value,
      page: typePaginDom.value.current,
      status: '',
    }
    await getTypeList(data).then((res) => {
      typeList.value = res.data.data.rows
      typeTotal.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 添加分类
  const addType = () => {
    typeForm.title = '添加分类'
    typeForm.status = false
    typeForm.name = ''
    addDialog.value = true
  }

  // 修改分类
  const viewTypeDetail = (obj) => {
    typeForm.title = '编辑分类'
    typeForm.status = obj.status
    typeForm.name = obj.name
    typeForm.id = obj.id
    addDialog.value = true
  }

  // 封装保存数据的方法
  const saveDataMethod = (method, data, dialog, getData, load) => {
    load.value = true
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        dialog.value = false
        load.value = false
        getData()
      } else {
        ElMessage({
          message: res.data.message,
          type: 'warning',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        load.value = false
        return
      }
    })
  }

  // 保存分类数据
  const saveType = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    const data = {
      id: typeForm.id,
      name: typeForm.name,
      status: typeForm.status,
    }
    formEl.validate((valid) => {
      if (valid) {
        if (typeForm.title == '添加分类') {
          saveDataMethod(saveUserType, data, addDialog, getTypeData, typeLoading)
        } else {
          saveDataMethod(saveUserType, data, addDialog, getTypeData, typeLoading)
        }
      }
    })
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 封装修改状态的方法
  const changeDisable = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的分类`,
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确认${type}选中的分类?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
        })
      } else {
        await method(arr).then((res) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (dialog == 1) {
            addDialog.value = false
          }
        })
      }
      selecttion.value = []
      typeTable.value.clearSelection()
      getTypeData()
    })
  }

  // 批量启用/禁用
  const changeStatus = (n) => {
    if (n == 1) {
      changeDisable('启用', changeType, selecttion.value, false, '')
    }
    if (n == 2) {
      changeDisable('禁用', changeType, selecttion.value, true, '')
    }
    if (n == 3) {
      changeDisable('删除', deleteType, selecttion.value, 3, '')
    }
    if (n == 4) {
      changeDisable('删除', deleteType, [typeForm.id], 3, 1)
    }
  }

  defineExpose({ getTypeData })
</script>

<style scoped lang="scss">
  @import './CustomerType.scss';
  @import '../../index.scss';
</style>
